// pages/myself/merchant/AddBrand.js
let network = null;
let utils = null;
let api = null;
const app = getApp();
var Zan = require('../../../dist/index');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');

Page(Object.assign({}, Zan.Tab, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: null,
    name: null,
    classArray: [[], []],
    multiIndex: [0, 0],
    multiArray: [[], []],
    selectedType: null,
    typeId: null,
    brandCost: null,
    selectedIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    // 获取商户
    network._post_json(this, api.getTenant, {}, tenantSuccess);
    // 获取品牌分类
    network._post_json(this, api.getTenantType, {}, typeSuccess);
    // 品牌入驻所需的费用
    network._post_json(this, api.getBrandVip, {}, brandSuccess);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        wx.showLoading();
        wx.uploadFile({
          url: api.upload, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          success: function (res) {
            wx.hideLoading();
            console.log(res.data);
            let data = JSON.parse(res.data);
            if (data.status == 1) {
              if (data.data) {
                that.setData({
                  imgUrl: data.data
                })
              }
            } else {
              that.showZanTopTips(that.error, '图片上传成功');
            }
          },
          fail: function (res) {
            console.log(res);
            that.showZanTopTips(that.error, '网络连接出错');
          },
          complete: function () {
            wx.hideLoading();
          },
        })
      }
    })
  },

  bindNameInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },

  /**
   * 选择分类
   */
  bindMultiPickerChange: function (e) {
    let type1 = this.data.multiArray[0][e.detail.value[0]];
    let type2 = this.data.multiArray[1][e.detail.value[1]] ? this.data.multiArray[1][e.detail.value[1]] : '';
    this.setData({
      selectedType: type1 + " " + type2
    })
    if (type2) {
      this.setData({
        typeId: this.data.classArray[e.detail.value[0]].list[e.detail.value[1]].id
      })
    } else {
      this.setData({
        typeId: this.data.classArray[e.detail.value[0]].id
      })
    }
  },

  /**
   * 滚动分类
   */
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    if (e.detail.column == 0) {
      /**
       * 将品牌类型存入到二维组
       */
      let temp = [];
      for (var i = 0; i < this.data.classArray[e.detail.value].list.length; i++) {
        temp.push(this.data.classArray[e.detail.value].list[i].typeName);
      }
      this.data.multiArray[1] = temp;
    }

    this.setData({
      multiArray: this.data.multiArray,
    });
  },

  /**
   * 选择支付方式
   */
  selectedPay: function (e) {
    this.setData({
      selectedIndex: e.currentTarget.dataset.index
    })
  },

  pay: function (e) {
    if (!this.data.imgUrl) {
      this.showZanTopTips(this.prompt, '请先上传LOGO');
      return;
    }
    if (!this.data.name) {
      this.showZanTopTips(this.prompt, '请输入品牌名称');
      return;
    }
    if (!this.data.typeId) {
      this.showZanTopTips(this.prompt, '请选择行业分类');
      return;
    }
    // 订单类型type  1=开通云商  2=开通来店  3=开通商圈  4=开通小游戏  5=提交工单
    network._post_json(this, api.pay, { type: 3, total: this.data.brandCost[this.data.selectedIndex].pv, path: this.data.imgUrl, name: this.data.name, brandType: this.data.typeId, code: this.data.code, totalKey: this.data.brandCost[this.data.selectedIndex].pk }, paySuccess);
  }
}))

var tenantSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      code: res.data.data.recommendNo
    })
  }
}

/**
 * 获取品牌类型成功
 */
var typeSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      classArray: res.data.data
    })

    /**
     * 将品牌类型存入到二维组
     */
    let temp = [];
    for (var i = 0; i < that.data.classArray.length; i++) {
      temp.push(that.data.classArray[i].typeName);
    }
    that.data.multiArray[0] = temp;

    if (that.data.classArray.length > 0) {
      if (that.data.classArray[0].list.length > 0) {
        let temp2 = [];
        for (var i = 0; i < that.data.classArray[0].list.length; i++) {
          temp2.push(that.data.classArray[0].list[i].typeName);
        }
        that.data.multiArray[1] = temp2;
      }
    }

    that.setData({
      multiArray: that.data.multiArray
    })
  }
}

// 品牌入驻所需的费用
var brandSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      brandCost: res.data.data
    })
  }
}

// 创建订单
var paySuccess = function (that, res) {
  if (res.data.data) {
    let order = res.data.data;
    network._post_json(that, api.payPre, { appId: app.globalData.appId, orderNo: order.orderNo, businessAppId: app.globalData.businessAppId, OrderDesc: order.orderDesc, totalFee: order.total }, payPreSuccess);
  }
}

// 生成预支付订单
var payPreSuccess = function (that, res) {
  if (res.data.data) {
    // 支付
    wx.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function (res) {
        WxNotificationCenter.postNotificationName("RefreshMerchantBrand");
        wx.navigateBack();
      },
      fail: function (res) {

      }
    });
  }
}